package com.dk.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.data.Result;
import com.dk.dto.DtGoodsDto;
import com.dk.dto.DtItemDTO;
import com.dk.dto.DtOrderDto;
import com.dk.dto.DtOrderItemDto;
import com.dk.em.ResultEnum;
import com.dk.entity.*;
import com.dk.mapper.*;
import com.dk.vo.OrderByVo;
import com.dk.vo.UserGoodVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("goods")
@Api(value = "根据当前用户获取相关信息")
public class LoginGoodsController {

    @Autowired
    DtGoodsMapper dtGoodsMapper;

    @Autowired
    DtItemMapper dtItemMapper;

    @Autowired
    DtOrderMapper dtOrderMapper;

    @Autowired
    DtOrderItemMapper dtOrderItemMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DtFansMapper dtFansMapper;

    @Autowired DtUserMapper dtUserMapper;

    private Lock lock = new ReentrantLock(true);



    @GetMapping
    @ApiOperation(value = "我发布的")
    public Result statusNo(){


        //根据用户id查询没有卖出的商品
        //用map集合条件查询里面的条件使用and连接的
        Map<String,Object> map = new HashMap<>();
        map.put("sellerid",1);
        map.put("auditStatus",0);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.allEq(map, true);
        List<DtGoods> dtGoods = dtGoodsMapper.selectList(queryWrapper);
        //将返回值进行脱敏处理 ！集合只能使用json转换
        String s = JSONObject.toJSONString(dtGoods);
        List<DtGoodsDto> goodsDto = JSONObject.parseArray(s, DtGoodsDto.class);
        /*List<DtGoodsDto> goodsDto = new ArrayList<>();
        BeanUtils.copyProperties(dtGoods,goodsDto);*/

        //用map集合条件查询里面的条件使用and连接的
        Map<String,Object> mapTwo = new HashMap<>();
        mapTwo.put("sellerid",1);
        mapTwo.put("status",1);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.allEq(mapTwo,true);
        List<DtItem> list = dtItemMapper.selectList(queryWrapper1);
        //将返回值进行脱敏处理 ！集合只能使用json转换
        String s1 = JSONObject.toJSONString(list);
        List<DtItemDTO> dtItemDTOS = JSONObject.parseArray(s1, DtItemDTO.class);
        //转vo接收
        UserGoodVo userGoodVo = new UserGoodVo();
        userGoodVo.setGoodsDtoList(goodsDto);
        userGoodVo.setItemDtoList(dtItemDTOS);

        return Result.response(ResultEnum.SUCCESS).setData(userGoodVo);
    }

    @GetMapping("yes")
    @ApiOperation(value = "我卖出的")
    public Result statusYes(){
        //根据用户id查询卖出的商品
        //用map集合条件查询里面的条件使用and连接的
        Map<String,Object> map = new HashMap<>();
        map.put("sellerid",1);
        map.put("auditStatus",1);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.allEq(map, true);
        List<DtGoods> dtGoods = dtGoodsMapper.selectList(queryWrapper);
        //将返回值进行脱敏处理 ！集合只能使用json转换
        String s = JSONObject.toJSONString(dtGoods);
        List<DtGoodsDto> goodsDto = JSONObject.parseArray(s, DtGoodsDto.class);
        /*List<DtGoodsDto> goodsDto = new ArrayList<>();
        BeanUtils.copyProperties(dtGoods,goodsDto);*/

        //用map集合条件查询里面的条件使用and连接的
        Map<String,Object> mapTwo = new HashMap<>();
        mapTwo.put("sellerid",1);
        mapTwo.put("status",2);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.allEq(mapTwo,true);
        List<DtItem> list = dtItemMapper.selectList(queryWrapper1);
        //将返回值进行脱敏处理 ！集合只能使用json转换
        String s1 = JSONObject.toJSONString(list);
        List<DtItemDTO> dtItemDTOS = JSONObject.parseArray(s1, DtItemDTO.class);
        //转vo接收
        UserGoodVo userGoodVo = new UserGoodVo();
        userGoodVo.setGoodsDtoList(goodsDto);
        userGoodVo.setItemDtoList(dtItemDTOS);

        return Result.response(ResultEnum.SUCCESS).setData(userGoodVo);
    }

    @GetMapping("orderBy")
    @ApiOperation(value = "买到手的")
    public Result orderBy(){
        //根据用户id查询买到的商品
        //用map集合条件查询里面的条件使用and连接的
        Map<String,Object> mapOrder = new HashMap<>();
        mapOrder.put("user_id",1);
        mapOrder.put("status",2);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.allEq(mapOrder, true);
        DtOrder dtOrder = dtOrderMapper.selectOne(queryWrapper);
        Long orderId = dtOrder.getOrderId();
        //将返回值进行脱敏处理 ！集合只能使用json转换
        String s = JSONObject.toJSONString(dtOrder);
        DtOrderDto dtOrderDto = JSONObject.parseObject(s, DtOrderDto.class);

        /*
        不能使用BeanUtils方法
        List<DtGoodsDto> goodsDto = new ArrayList<>();
        BeanUtils.copyProperties(dtGoods,goodsDto);*/
        //根据用户id查询买到的商品的订单详情
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("order_id",orderId);
        DtOrderItem dtOrderItem = dtOrderItemMapper.selectOne(queryWrapper1);
        String s1 = JSONObject.toJSONString(dtOrderItem);
        DtOrderItemDto dtOrderItemDto = JSONObject.parseObject(s1, DtOrderItemDto.class);
        //将返回值进行脱敏处理 ！集合只能使用json转换
        //返回VO
        OrderByVo orderByVo = new OrderByVo();
        orderByVo.setDtOrderDto(dtOrderDto);
        orderByVo.setDtOrderItemDto(dtOrderItemDto);
        return Result.response(ResultEnum.SUCCESS).setData(orderByVo);
    }

    @GetMapping("see")
    @ApiOperation(value = "我关注的")
    public Result see(){
        //考虑到关注功能的访问率较高为了减轻数据库压力将当前用户id作为key，关注的用户信息作为value存入redis
        //因为开发环境先设置用户的id
        String uid = "1";
        List list1 = new ArrayList();
        if (redisTemplate.hasKey(uid)) {
            Object o = redisTemplate.boundValueOps(uid).get();
            String s = JSONObject.toJSONString(o);
            List<DtUser> dtUsers = JSONObject.parseArray(s, DtUser.class);
            Result.response(ResultEnum.SUCCESS).setData(dtUsers);
        }else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("fans_id",uid);
            List<DtFans> list = dtFansMapper.selectList(queryWrapper);
            for (DtFans dtFans : list) {
                Long id = dtFans.getUid();
                DtUser dtUser = dtUserMapper.selectById(id);
                list1.add(dtUser);
            }
            redisTemplate.boundValueOps(uid).set(list1);
        }
        return Result.response(ResultEnum.SUCCESS).setData(list1);

    }

    @PutMapping("lookOrder")
    @ApiOperation(value = "商品的浏览次数自增")
    @ApiImplicitParam(name = "orderId", value = "商品的id", required = true, paramType = "query")
    public void lookOrder(String orderId){
        //考虑到页面并发量很大所以为了保证原子性使用lock可重入锁
        lock.lock();
        try {
            //每一次查询线路 为了实现排行榜功能。需要使zset集合中所对应的key的score自增
            ZSetOperations zSet = redisTemplate.opsForZSet();
            String key = "hot:pv";
            zSet.incrementScore(key,orderId,1);
        }finally {
            lock.unlock();
        }
    }
    @GetMapping("getHot")
    @ApiOperation(value = "商品的浏览次数展示")
    @ApiImplicitParam(name = "orderId", value = "商品的id", required = true, paramType = "query")
    public Result getHot(String orderId) {
        String key = "hot:pv";
        ZSetOperations zSet = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<Object>> set = zSet.reverseRangeWithScores(key, 0, -1);
        Iterator<ZSetOperations.TypedTuple<Object>> iterator = set.iterator();
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple<Object> next = iterator.next();
            String rid = (String) next.getValue();
            if (rid.equals(orderId)) {
                Double score = next.getScore();
                return Result.response(ResultEnum.SUCCESS).setData(score);
            }
        }
        return Result.response(ResultEnum.SUCCESS).setData(0);
    }

    @GetMapping("fans")
    @ApiOperation(value = "关注我的")
    public Result fans(){
        //考虑到关注功能的访问率较高为了减轻数据库压力将当前用户id作为key，关注的用户信息作为value存入redis
        //因为开发环境先设置用户的id
        String uid = "1";
        //不同用户的key
        String user =uid+"fans";
        List list1 = new ArrayList();
        if (redisTemplate.hasKey(user)) {
            Object o = redisTemplate.boundValueOps(user).get();
            String s = JSONObject.toJSONString(o);
            List<DtUser> dtUsers = JSONObject.parseArray(s, DtUser.class);
            return Result.response(ResultEnum.SUCCESS).setData(dtUsers);
        }else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("follow_id",uid);
            List<DtFans> list = dtFansMapper.selectList(queryWrapper);
            for (DtFans dtFans : list) {
                Long id = dtFans.getUid();
                DtUser dtUser = dtUserMapper.selectById(id);
                list1.add(dtUser);
            }
            redisTemplate.boundValueOps(user).set(list1);
        }
        return Result.response(ResultEnum.SUCCESS).setData(list1);

    }


}

